package com.util;

import org.junit.Test;

import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;


public class OptionalDemo {
    @Test
    public void test01() {
        String s = null;
    }

    @Test
    public void of() {
        String s = null;
        Optional.ofNullable(s);
        //抛出异常
        Optional.of(s);
    }

    @Test
    public void orElse() throws Exception {
        String s = "sss";
        Supplier<String> f = () -> {
            System.out.println("该方法被执行");
            return "aa";
        };

        //当s不为空的时候，也会执行f方法
        System.out.println(Optional.ofNullable(s).orElse(f.get()));

        //只有当s为空的时候执行f方法
        System.out.println(Optional.ofNullable(s).orElseGet(f));
        Optional.ofNullable(s).orElseThrow(() -> new Exception("空指针异常"));

    }

}
